package com.ruoyi.web.controller.api;

import com.ijpay.core.kit.IpKit;
import com.ijpay.core.kit.WxPayKit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.AvataSignUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.domain.pay.CreatePayReqVO;
import com.ruoyi.web.entity.pay.response.CreatePayResponse;
import com.ruoyi.web.service.ApiPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
@Api(tags = "支付模块")
@RestController
@RequestMapping("/api/pay")
public class ApiPayController extends BaseController
{
    @Autowired
    private ApiPayService apiPayService;


    @ApiOperation(value = "创建微信订单")
    @PostMapping("/traderWxPay")
    @Log(title = "创建微信订单", businessType = BusinessType.INSERT)
    public AjaxResult traderWxPay(HttpServletRequest request, CreatePayReqVO wxPayReqVO) {
        logger.info("微信支付");

        String realIp = IpKit.getRealIp(request);
        if (StringUtils.isEmpty(realIp)) {
            realIp = "127.0.0.1";
        }
        wxPayReqVO.setUserId(ServletUtils.getLoginUid());
        wxPayReqVO.setRealIp(realIp);

        CreatePayResponse orderId = apiPayService.traderWxPay(wxPayReqVO);

        return success(orderId);
    }

    @PostMapping(value = "/payV2Notify")
    @Log(title = "微信支付回调", businessType = BusinessType.INSERT)
    public String payV2Notify(@RequestBody String xmlData) throws ParseException {
        Map<String, String> map = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info("微信回调开始了");
        //这里我只进行了部分回调信息的保存，更多参数请查看微信支付官方api:
        // https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7&index=8
//        Map<String, String> resultMap = WxPayKit.xmlToMap(xmlData);
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("transaction_id", "4200001622202211168847884221");//微信支付订单号
        resultMap.put("out_trade_no", "2023112816004228606"); //商户订单号
        resultMap.put("nonce_str", "ae0c83f1797b490abb37fa6a625950d8");
        resultMap.put("bank_type", "OTHERS"); 
        resultMap.put("openid", "o5hWT5B5JUzCiaIIKRouo_JnWpeM"); 
        resultMap.put("sign", "E06E75D4AA5D613E8A2FCDB744503B29"); 
        resultMap.put("fee_type", "CNY"); 
        resultMap.put("mch_id", "1510345901"); 
        resultMap.put("cash_fee", "1"); // 现金支付
        resultMap.put("appid", "wxa4c9e3c670deadc4");
        resultMap.put("total_fee", "1");
        resultMap.put("trade_type", "JSAPI"); 
        resultMap.put("result_code", "SUCCESS"); 
        resultMap.put("return_code", "SUCCESS"); 
        logger.info("resultMap:" + resultMap);
//            10:29:59.190 [http-nio-7070-exec-20] INFO  c.b.p.a.PayController - [payV2Notify,129] - resultMap:
//            {transaction_id=4200001622202211168847884221, nonce_str=ae0c83f1797b490abb37fa6a625950d8, bank_type=OTHERS,
//            openid=o5hWT5B5JUzCiaIIKRouo_JnWpeM, sign=E06E75D4AA5D613E8A2FCDB744503B29, fee_type=CNY, mch_id=1510345901,
//            cash_fee=1, out_trade_no=9079d6dc90cb41ce8e743f068d4be285, appid=wxa4c9e3c670deadc4,
//            total_fee=1, trade_type=JSAPI, result_code=SUCCESS, time_end=20221116102958,
//            is_subscribe=N, return_code=SUCCESS}
        /*----------------------分割线，下面的是业务代码，根据自己业务进行修改--------------------------*/
        //订单成功业务处理
        if ("SUCCESS".equals(resultMap.get("result_code"))) {
            // 根据resultMap处理订单业务
            apiPayService.finishV2Order(resultMap);
        }
        /*----------------------分割线，业务结束--------------------------*/

        map.put("return_code", "SUCCESS");
        map.put("return_msg", "OK");
        return AvataSignUtils.getMapToXml(map);
    }
//
//    @PostMapping("/alipayNotify")
//    @Log(title = "支付宝支付回调", businessType = BusinessType.INSERT)
//    public void alipayNotify(@NotNull HttpServletRequest req, HttpServletResponse resp) throws AlipayApiException, IOException {
//        Map<String, String> params = new HashMap<String, String>();
//        Map requestParams = req.getParameterMap();
//        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
//            String name = (String) iter.next();
//            String[] values = (String[]) requestParams.get(name);
//            String valueStr = "";
//            for (int i = 0; i < values.length; i++) {
//                valueStr = (i == values.length - 1) ? valueStr + values[i]
//                        : valueStr + values[i] + ",";
//            }
//            params.put(name, valueStr);
//        }
//        String result = apiPayService.finishAlipayOrder(params);
//        resp.getWriter().write(result);
//    }
//
    @ApiOperation(value = "测试微信支付")
    @PostMapping("/test")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "total_fee", value = "1身高2行业3年型4学历", required = true),
            @ApiImplicitParam(name = "out_trade_no", value = "1身高2行业3年型4学历", required = true),
            @ApiImplicitParam(name = "transaction_id", value = "1身高2行业3年型4学历", required = true),
    })
    public void test(String total_fee, String out_trade_no, String transaction_id) {

        Map<String, String> resultMap = new HashMap<>();

        resultMap.put("total_fee", total_fee);
        resultMap.put("out_trade_no", out_trade_no);
        resultMap.put("transaction_id", transaction_id);

        apiPayService.finishV2Order(resultMap);

    }
//
//    @ApiOperation(value = "微信支付")
//    @PostMapping("/wechatPay")
//    @Log(title = "微信支付", businessType = BusinessType.INSERT)
//    public SimpleResponse<CreatePayResponse> wechatPay(HttpServletRequest request, CreateWxPayReqVO wxPayReqVO) {
//        logger.info("微信支付");
//
//        if (wxPayReqVO.getBankId() == null || wxPayReqVO.getUid() == null) {
//            throw new ServiceException(PoaErrorEnums.UNAUTHORIZED.getData());
//        }
//
//        String realIp = IpKit.getRealIp(request);
//        if (StringUtils.isEmpty(realIp)) {
//            realIp = "127.0.0.1";
//        }
//        if (ServletUtils.getLoginUid() != null && ServletUtils.getLoginUid() != 0) {
//            wxPayReqVO.setUid(ServletUtils.getLoginUid());
//        }
//        wxPayReqVO.setRealIp(realIp);
//
//        PoaStore product = productService.selectProduct(wxPayReqVO.getBankId());
//        if (product == null) {
//            throw new ServiceException("商品不存在");
//        }
//
//        // 根据bankId查询商品是否存在, 查询openid
//        Long uid = wxPayReqVO.getUid();
//        Long bankId = product.getProductId();
//        double amount = product.getSalePrice() != null ? product.getSalePrice() : product.getPrice();
//        Integer tradeType = wxPayReqVO.getTradeType();
//        // 小程序判断openId
//        String openId = wxPayReqVO.getOpenId();
//        CreateOrderVO orderVO = new CreateOrderVO();
//        orderVO.setOpenId(openId);
//        orderVO.setAmount(amount);
//        orderVO.setUid(uid);
//        orderVO.setRealIp(wxPayReqVO.getRealIp());
//        orderVO.setBankId(bankId);
//        orderVO.setCtid(wxPayReqVO.getCtid() == null ? 0 : wxPayReqVO.getCtid());
//        orderVO.setTradeType(tradeType);
//
//        // 扩展字段
//        PoaCashFlowExtend extend = new PoaCashFlowExtend();
//        extend.setUid(uid);
//        extend.setNoId(product.getProductId());
//        orderVO.setExtend(JSON.toJSONString(extend));
//        CreatePayResponse payResponse = apiPayService.createWx(orderVO);
//        return SimpleResponse.successWith(payResponse);
//    }
//
//    @ApiOperation(value = "支付宝网页支付")
//    @PostMapping("ali-web-Pay")
//    @Log(title = "支付宝网页支付", businessType = BusinessType.INSERT)
//    public SimpleResponse<String> aliWebPay(HttpServletRequest request, CreateWxPayReqVO wxPayReqVO) {
//        logger.info("支付宝网页支付");
//
//        if (wxPayReqVO.getUid() == null || wxPayReqVO.getBankId() == null) {
//            throw new ServiceException(PoaErrorEnums.UNAUTHORIZED.getData());
//        }
//
//        String realIp = IpKit.getRealIp(request);
//        if (StringUtils.isEmpty(realIp)) {
//            realIp = "127.0.0.1";
//        }
//        if (ServletUtils.getLoginUid() != null && ServletUtils.getLoginUid() != 0) {
//            wxPayReqVO.setUid(ServletUtils.getLoginUid());
//        }
//        wxPayReqVO.setRealIp(realIp);
//
//        PoaStore product = productService.selectProduct(wxPayReqVO.getBankId());
//        if (product == null) {
//            throw new ServiceException("商品不存在");
//        }
//
//        double amount = product.getSalePrice() != null ? product.getSalePrice() : product.getPrice();
//
//        CreateOrderVO orderVO = new CreateOrderVO();
//        orderVO.setAmount(amount);
//        orderVO.setUid(wxPayReqVO.getUid());
//        orderVO.setBankId(product.getProductId());
//        orderVO.setCtid(wxPayReqVO.getCtid() == null ? 0 : wxPayReqVO.getCtid());
//        orderVO.setExtend(wxPayReqVO.getReturnUrl());
//
//        String orderUrl = apiPayService.createAliWebPay(orderVO);
//
//        return SimpleResponse.successWith(orderUrl);
//    }
    

}
